package com.ruoyi.web.controller.system;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.bo.SysTenantAddBo;
import com.ruoyi.system.domain.bo.SysTenantEditBo;
import com.ruoyi.system.domain.bo.SysTenantQueryBo;
import com.ruoyi.system.domain.vo.SysTenantExportVo;
import com.ruoyi.system.domain.vo.SysTenantVo;
import com.ruoyi.system.service.ISysTenantService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 租户Controller
 *
 * @author lingdeng
 * @date 2021-07-24
 */
@Validated
@Api(value = "租户控制器", tags = {"租户管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/system/tenant")
public class SysTenantController extends BaseController {

    private final ISysTenantService iSysTenantService;

    private final ISysUserService userService;

    /**
     * 查询租户列表
     */
    @ApiOperation("查询租户列表")
    @PreAuthorize("@ss.hasPermi('system:tenant:list')")
    @GetMapping("/list")
    public TableDataInfo<SysTenantVo> list(@Validated SysTenantQueryBo bo) {
        return iSysTenantService.queryPageList(bo);
    }

    /**
     * 导出租户列表
     */
    @ApiOperation("导出租户列表")
    @PreAuthorize("@ss.hasPermi('system:tenant:export')")
    @Log(title = "租户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@Validated SysTenantQueryBo bo, HttpServletResponse response) {
        List<SysTenantVo> list = iSysTenantService.queryList(bo);
        List<SysTenantExportVo> listVo = BeanUtil.copyToList(list, SysTenantExportVo.class);
        ExcelUtil.exportExcel(listVo, "租户", SysTenantExportVo.class, response);
    }

    /**
     * 获取租户详细信息
     */
    @ApiOperation("获取租户详细信息")
    @PreAuthorize("@ss.hasPermi('system:tenant:query')")
    @GetMapping("/{tenantId}")
    public AjaxResult<SysTenantVo> getInfo(@NotNull(message = "主键不能为空")
                                           @PathVariable("tenantId") Long tenantId) {
        return AjaxResult.success(iSysTenantService.queryById(tenantId));
    }

    /**
     * 新增租户
     */
    @ApiOperation("新增租户")
    @PreAuthorize("@ss.hasPermi('system:tenant:add')")
    @Log(title = "租户", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated @RequestBody SysTenantAddBo bo) {
        return toAjax(iSysTenantService.insertByAddBo(bo)>0 ? 1 : 0);
    }

    /**
     * 修改租户
     */
    @ApiOperation("修改租户")
    @PreAuthorize("@ss.hasPermi('system:tenant:edit')")
    @Log(title = "租户", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated @RequestBody SysTenantEditBo bo) {
        return toAjax(iSysTenantService.updateByEditBo(bo) ? 1 : 0);
    }

    /**
     * 删除租户
     */
    @ApiOperation("删除租户")
    @PreAuthorize("@ss.hasPermi('system:tenant:remove')")
    @Log(title = "租户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{tenantIds}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")
                                   @PathVariable Long[] tenantIds) {
        return toAjax(iSysTenantService.deleteWithValidByIds(Arrays.asList(tenantIds), true) ? 1 : 0);
    }

    /**
     * 查询已分配用户租户列表
     */
    @ApiOperation("查询已分配用户租户列表")
    @PreAuthorize("@ss.hasPermi('system:tenant:list')")
    @GetMapping("/authUser/allocatedList")
    public TableDataInfo<SysUser> allocatedList(SysUser user, PageQuery pageQuery) {
        return userService.selectAllocatedList(user, pageQuery);
    }

    /**
     * 查询未分配用户租户列表
     */
    @ApiOperation("查询未分配用户租户列表")
    @PreAuthorize("@ss.hasPermi('system:tenant:list')")
    @GetMapping("/authUser/unallocatedList")
    public TableDataInfo<SysUser> unallocatedList(SysUser user, PageQuery pageQuery) {
        return userService.selectUnallocatedList(user, pageQuery);
    }

    /**
     * 取消授权用户
     */
    @ApiOperation("取消授权用户")
    @PreAuthorize("@ss.hasPermi('system:tenant:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(@RequestBody SysUser user) {
        return toAjax(iSysTenantService.deleteAuthUser(user));
    }

    /**
     * 批量取消授权用户
     */
    @ApiOperation("批量取消授权用户")
    @PreAuthorize("@ss.hasPermi('system:tenant:edit')")
    @Log(title = "租户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public AjaxResult cancelAuthUserAll(Long tenantId, Long[] userIds) {
        return toAjax(iSysTenantService.deleteAuthUsers(tenantId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @ApiOperation("批量选择用户授权")
    @PreAuthorize("@ss.hasPermi('system:tenant:edit')")
    @Log(title = "租户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(Long tenantId, Long[] userIds) {
        return toAjax(iSysTenantService.insertAuthUsers(tenantId, userIds));
    }

}
